import { Component, OnInit } from '@angular/core';
import { Router,NavigationExtras } from '@angular/router';
import { ActionSheetController,AlertController,ToastController  } from '@ionic/angular';
import { AuthTokenService } from '@services/auth-token.service';
import {HttpClient,HttpHeaders, HttpErrorResponse} from "@angular/common/http";
import {environment} from 'src/environments/environment';
import { EncryptService } from '@services/encrypt.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AutoLoginType } from '@services/common-service.service';
import { EventEmitterService,EventName } from '@services/event-emitter.service';
import { DefaultLanguageService } from '@services/default-language.service';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector: 'app-account-security',
  templateUrl: './account-security.page.html',
  styleUrls: ['./account-security.page.scss'],
})
export class AccountSecurityPage implements OnInit {

  public appUser:any = {
    mobileNumber:'',
    faceIdLogin:false,
    fingerPrintLogin:false,
    email:''
  };

  private i18n:any;

  constructor(private router:Router,
    private alertController: AlertController,
    private commonService:CommonService,
    private authTokenService:AuthTokenService,
    public http:HttpClient,
    private defaultLanguageService:DefaultLanguageService,
    private translate:TranslateService,
    private encryptService:EncryptService,
    private toastController: ToastController,
    private eventEmitterService:EventEmitterService) {
      
    }

  ngOnInit() {
    this.initLanguage();
    this.getAppUser();
    this.initEventMonitor();
  }

  initLanguage(){
    this.i18n = this.commonService.initTranslate(['myAccount.setting.accountScurity']); 
  }

  initEventMonitor(){
    this.eventEmitterService.eventEmit.subscribe((value: any) => {
      if(value == EventName.EMAIL_CHANGED
        || value == EventName.MOBILE_CHANGED
        || value == EventName.TOUCH_ID_LOGIN_CHANGED) {
        this.getAppUser();
      }
    });
  }

  async getAppUser(){
    let appUserId = this.authTokenService.getAppUserId();
    let result = await this.commonService.getAppUser(appUserId);
    result.subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        this.appUser = response.responseBody;
      }
    });
  }

  changeFingerPrintLoginEnable(){
    if(!this.appUser.fingerPrintLogin){
      this.enableFingerPrintPrompt()
    }else{
      this.closeFingerPrintPrompt();
    }
  }

  async enableFingerPrintPrompt() {
    const alert = await this.alertController.create({
      header: this.i18n.please_enter_login_pwd,
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder: this.i18n.password
        }
      ],
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            this.appUser.fingerPrintLogin = false;
          }
        }, {
          text: this.i18n.confirm,
          handler: (data) => {
            if(!data.password){
              return false;
            }
            this.commonService.checkPassword(data.password).subscribe((response:CommonResponse) => {
              if(response.isSuccess && response.responseBody.isPass){
                //this.enableOrCloseTouchId(true,AutoLoginType.FINGER_PRINT);
                this.router.navigate(['/tabs/myAccount/setting/fingerprint-setup']);
              }else{  
                this.appUser.fingerPrintLogin = false;
                this.commonService.commonToast(ToastColor.warning,this.i18n.passwordIncorrent);
              }
            },
            (errorResponse:HttpErrorResponse)=>{
              this.appUser.fingerPrintLogin = false;
              this.commonService.errorRespCommonToast(errorResponse,this.i18n);
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async closeFingerPrintPrompt() {
    const alert = await this.alertController.create({
      header: this.i18n.close_touch_id,
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            this.appUser.fingerPrintLogin = true;
          }
        }, {
          text: this.i18n.confirm,
          handler: () => {
            this.enableOrCloseTouchId(false,AutoLoginType.FINGER_PRINT);
          }
        }
      ]
    });
    await alert.present();
  }

  enableOrCloseTouchId(enable:boolean,autoLoginType:AutoLoginType){
    var api = "/scm/app/enableOrCloseAutoLogin.do";
    var requestJson = {
      'appUserId':this.authTokenService.getAppUserId(),
      'enable':enable,
      'deviceId':this.authTokenService.getDeviceId(),
      'autoLoginType':autoLoginType.toString()
    }
    this.http.post(api,requestJson).subscribe((response:CommonResponse)=>{
      if(response.isSuccess && response.responseBody){
        this.commonService.commonToast(ToastColor.success,this.i18n.operate_success);
        if(enable && response.responseBody.autoLoginSwitch){
          let loginToken = response.responseBody.loginToken;
          this.authTokenService.setLoginToken(loginToken);
        }else{
          this.authTokenService.removeLoginToken();
        }
      }else{
        this.appUser.fingerPrintLogin = !enable;
        this.commonService.commonToast(ToastColor.warning);
      }
    },(errorResponse)=>{
      this.appUser.fingerPrintLogin = !enable;
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
    });
  }

  toEmailPage(){
    if(!this.appUser.email){
      this.router.navigate(['/tabs/myAccount/setting/account-security/email-create']);
    }else{
      let navigationExtras: NavigationExtras = {
        queryParams: { 'email': this.appUser.email }
      };
      this.router.navigate(['/tabs/myAccount/setting/account-security/email-amend'],navigationExtras);
    }
  }
  
}
